<script setup>
import { User, Lock} from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import {userRegisterService,userLoginService} from '@/api/user.js'
import {useUserStore} from '@/stores/index.js'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const isRegister = ref(false)
const form = ref()

const formModel = ref({
  username: '',
  password: '',
  repassword: '',
})

//1、非空校验 required: true   message消息提示， trigger触发校验时机 blur change
//2、长度校验 min:xx max:xx
//3、正则校验 pattern：正则规则
//4、自定义校验 => 自己写校验逻辑 （校验函数）
//  validator: (rule, value, callback)
//  (1) rule 当前校验规则相关的信息
//  (2) value 当前所校验的表单元素目前的表单值
//  (3) callback 回调函数，用于接收校验结果，参数：校验结果，校验通过为空，不通过为错误信息
//      - callback() 校验成功
//      - callback( new Error(错误信息) ) 校验失败
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'change' },
    { min: 5, max: 10, message: 'Length should be 5 to 10', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { pattern: /^[a-zA-Z0-9_-]{6,12}$/, message: '请输入6-12位字母数字下划线', trigger: 'blur' },
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { pattern: /^[a-zA-Z0-9_-]{6,12}$/, message: '请输入6-12位字母数字下划线', trigger: 'blur' },
    {
      //判断 value 和当前 form 中的 password 是否一致
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

const userStore = useUserStore()
const router = useRouter()

const register = async () => {
  await form.value.validate()
  console.log('开始注册请求')
  await userRegisterService(formModel.value)
  ElMessage.success('注册成功')
  isRegister.value = false
}

const login = async () => {
  await form.value.validate()

  const res = await userLoginService(formModel.value)
  userStore.setToken(res.data.token)
  console.log(userStore.token)
  router.push('/')
}

watch(isRegister, () => {
  console.log('isRegister', isRegister)
  formModel.value = {
    username: '',
    password: '',
    repassword: ''
  }
})
</script>

<template>
  <!--  el-row 一行24分



-->
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="formModel.repassword"
            :prefix-icon="Lock" type="password" placeholder="请输入再次密码">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="register"
            class="button" type="primary" auto-insert-space>
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false"> ← 返回 </el-link>
        </el-form-item>
      </el-form>
      <el-form :model="formModel" :rules="rules" ref="form" size="large" autocomplete="off" v-else>
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="login"
            class="button" type="primary" auto-insert-space>登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true"> 注册 → </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background:
      url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
